package com.able.concurrency.t4;

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TransferQueue;

/**
 * @author abel.he
 * @data 2018/10/25 16:20
 * @describe
 * 转移队列， 使用 transfer 方法，实现数据的即时处理。没有消费者，就阻塞。
 *
 */
public class Test7_TransferQueue {

    TransferQueue<String> transferQueue = new LinkedTransferQueue<>();

    public static void main(String[] args) throws InterruptedException {
        final Test7_TransferQueue transferQueue = new Test7_TransferQueue();

        /*
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "begin");
                try {
                    System.out.println(transferQueue.transferQueue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "take").start();

        TimeUnit.SECONDS.sleep(2);
        transferQueue.transferQueue.put("hello transfer");
        */

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    transferQueue.transferQueue.transfer("test string");
//                    transferQueue.transferQueue.add("test string");
                    System.out.println("add ok");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + " thread begin " );
                    System.out.println(Thread.currentThread().getName() + " - " + transferQueue.transferQueue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "output thread").start();
    }

}
